// pages/postAdd/index.js
Page({
    data: {
        images: [], // 上传的图片列表
        title: '', // 帖子标题
        content: '', // 帖子内容
        selectedProduct: null, // 选择的关联产品
        canPreview: false, // 是否可以预览
        canPublish: false, // 是否可以发布
        showPage: false,
        ips: [], // IP列表
        selectedIp: null, // 选择的IP ID
        selectedIpName: '', // 选择的IP名称
        series: [], // 系列列表
        selectedSeries: null, // 选择的系列ID
        selectedSeriesName: '', // 选择的系列名称
        products: [], // 产品列表
        selectedProducts: [], // 已选择的产品列表
    },

    onLoad() {
        this.checkFormStatus();
        this.loadIpList();
    },
    // 加载数据
    loadIpList() {
        const that = this;
        wx.showLoading({
            title: '加载中...',
            mask: true
        });

        wx.cloud.callFunction({
            name: 'getIpList',
        }).then(res => {
            wx.hideLoading();
            console.log(res);
            if (res.result && res.result.success) {
                // 成功获取IP列表
                let newArr = res.result.data.filter(item => {
                    return item.id != 'other'
                })
                that.setData({
                    ips: newArr
                });
            } else {
                wx.showToast({
                    title: '获取IP列表失败',
                    icon: 'none'
                });
            }
        }).catch(err => {
            wx.hideLoading();
            console.error('调用云函数失败', err);
            wx.showToast({
                title: '网络错误，请稍后再试',
                icon: 'none'
            });
        });
    },
    // 获取系列列表
    loadSeriesList: function (ipId) {
        const that = this;
        wx.showLoading({
            title: '加载中...',
            mask: true
        });

        wx.cloud.callFunction({
            name: 'getSeriesList',
            data: {
                ipId: ipId
            },
            success: (res) => {
                wx.hideLoading();
                if (res.result && res.result.success) {
                    // 成功获取系列列表
                    that.setData({
                        series: res.result.data,
                        products: [],
                        selectedSeries: '',
                        selectedSeriesName: '',
                    });
                } else {
                    wx.showToast({
                        title: '获取系列列表失败',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                wx.hideLoading();
                console.error('调用云函数失败', err);
                wx.showToast({
                    title: '网络错误，请稍后再试',
                    icon: 'none'
                });
            }
        });
    },

    // 获取产品列表
    loadProductList: function (seriesId) {
        const that = this;

        wx.showLoading({
            title: '加载中...',
            mask: true
        });

        wx.cloud.callFunction({
            name: 'getProductList',
            data: {
                seriesId: seriesId
            },
            success: (res) => {
                wx.hideLoading();

                if (res.result && res.result.success) {
                    // 成功获取产品列表
                    that.setData({
                        products: res.result.data,
                    });
                } else {
                    wx.showToast({
                        title: '获取产品列表失败',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                wx.hideLoading();
                console.error('调用云函数失败', err);
                wx.showToast({
                    title: '网络错误，请稍后再试',
                    icon: 'none'
                });
            }
        });
    },
    // 选择IP
    selectIp(e) {
        console.log(e);
        const ipId = e.currentTarget.dataset.ipId;
        const ipName = e.currentTarget.dataset.ipName;

        this.setData({
            selectedIp: ipId,
            selectedIpName: ipName,
            selectedSeries: null,
            selectedSeriesName: '',
            products: []
        });
        this.loadSeriesList(ipId);
    },
    // 取消选择Ip
    removeIp() {
        this.setData({
            selectedIp:null,
            selectedIpName:'',
            selectedSeries: null,
            selectedSeriesName: "",
            series: [],
            products: [],
            selectedProducts: []
        });
        
    },
    // 选择系列
    selectSeries(e) {
        console.log(e);
        const seriesId = e.currentTarget.dataset.seriesId;
        const seriesName = e.currentTarget.dataset.seriesName;

        this.setData({
            selectedSeries: seriesId,
            selectedSeriesName: seriesName,
            products: []
        });
        this.loadProductList(seriesId);
    },
    // 取消选择系列
    removeSeries() {
        this.setData({
            selectedSeries: null,
            selectedSeriesName: "",
            series: [],
            products: [],
            selectedProducts: []
        });
        this.loadSeriesList(this.data.selectedIp);
    },
    // 切换产品选择状态
    toggleProduct(e) {
        console.log(e);
        const productId = e.currentTarget.dataset.productId;
        const productName = e.currentTarget.dataset.productName;

        const isSelected = this.data.selectedProducts.some(product => product.productId === productId);

        if (isSelected) {
            // 移除已选产品
            const selectedProducts = this.data.selectedProducts.filter(product => product.productId !== productId);
            this.setData({
                selectedProducts
            });
        } else {
            // 添加新选产品
            const newProduct = {
                ipId: this.data.selectedIp,
                ipName: this.data.selectedIpName,
                seriesId: this.data.selectedSeries,
                seriesName: this.data.selectedSeriesName,
                productId,
                productName
            };

            const selectedProducts = [...this.data.selectedProducts, newProduct];
            this.setData({
                selectedProducts
            });
        }
    },

    // 移除已选产品
    removeProduct(e) {
        console.log(e);
        const index = e.currentTarget.dataset.index;
        const selectedProducts = [...this.data.selectedProducts];
        selectedProducts.splice(index, 1);
        this.setData({
            selectedProducts
        });
    },

    // 检查产品是否已选
    isProductSelected(productId) {
        return this.data.selectedProducts.some(product => product.productId === productId);
    },

    // 保存已选产品
    saveSelectedProducts() {
        console.log(this.data.selectedProducts);
        this.setData({
            showPage: false
        });
        this.checkFormStatus();
    },
    // 选择图片
    chooseImage() {
        wx.chooseMedia({
            count: 9 - this.data.images.length,
            mediaType: ['image'],
            sourceType: ['album', 'camera'],
            success: (res) => {
                const tempFiles = res.tempFiles;
                const tempPaths = tempFiles.map(file => file.tempFilePath);
                this.setData({
                    images: [...this.data.images, ...tempPaths]
                });
                this.checkFormStatus();
            }
        });
    },

    // 预览图片
    previewImage(e) {
        const index = e.currentTarget.dataset.index;
        const images = this.data.images;
        wx.previewImage({
            current: images[index],
            urls: images
        });
    },

    // 删除图片
    deleteImage(e) {
        const index = e.currentTarget.dataset.index;
        const images = this.data.images;
        images.splice(index, 1);
        this.setData({
            images
        });
        this.checkFormStatus();
    },

    // 输入标题
    onTitleInput(e) {
        this.setData({
            title: e.detail.value
        });
        this.checkFormStatus();
    },

    // 输入内容
    onContentInput(e) {
        this.setData({
            content: e.detail.value
        });
        this.checkFormStatus();
    },

    // 选择产品
    selectProduct() {
        // wx.navigateTo({
        //     url: '/pages/select-product/index'
        // });
        console.log(1);
        this.setData({
            showPage: true
        });

    },
    // 移除已选产品
    removeProduct(e) {
        const index = e.currentTarget.dataset.index;
        const selectedProducts = [...this.data.selectedProducts];
        selectedProducts.splice(index, 1);
        this.setData({
            selectedProducts
        });
        this.checkFormStatus();
    },
    // 检查表单状态
    checkFormStatus() {
        const canPreview = this.data.images.length > 0 && this.data.title.trim() !== '';
        const canPublish = canPreview && this.data.selectedProducts.length > 0;

        this.setData({
            canPreview,
            canPublish
        });
    },


    // 发布帖子
    publishPost() {
        if (!this.data.canPublish) {
            wx.showToast({
                title: '请补全信息',
                icon: 'none'
            });
            return;
        }

        wx.showLoading({
            title: '发布中...'
        });

        // 上传图片到云存储
        this.uploadImages().then(fileIds => {
            // 调用云函数发布帖子
            wx.cloud.callFunction({
                name: 'createPost',
                data: {
                    title: this.data.title,
                    content: this.data.content,
                    images: fileIds,
                    productRelations: this.data.selectedProducts,
                    userInfo: wx.getStorageSync('userInfo')
                }
            }).then(res => {
                wx.hideLoading();

                if (res.result && res.result.success) {
                    wx.showToast({
                        title: '发布成功',
                        icon: 'none'
                    });
                    setTimeout(() => {
                        wx.navigateBack();
                    }, 1500);
                } else {
                    wx.showToast({
                        title: res.result.message || '发布失败',
                        icon: 'none'
                    });
                }
            }).catch(err => {
                wx.hideLoading();
                console.error('发布帖子失败', err);
                wx.showToast({
                    title: '发布失败',
                    icon: 'none'
                });
            });
        }).catch(err => {
            wx.hideLoading();
            console.error('上传图片失败', err);
            wx.showToast({
                title: '上传图片失败',
                icon: 'none'
            });
        });
    },

    // 上传图片到云存储
    uploadImages() {
        return new Promise((resolve, reject) => {
            if (this.data.images.length === 0) {
                resolve([]);
                return;
            }

            const uploadTasks = this.data.images.map((image, index) => {
                return new Promise((resolve, reject) => {
                    const ext = image.match(/\.[^.]+?$/)[0];
                    const cloudPath = `community/posts/${Date.now()}-${index}${ext}`;

                    wx.cloud.uploadFile({
                        cloudPath,
                        filePath: image,
                        success: res => {
                            resolve(res.fileID);
                        },
                        fail: err => {
                            reject(err);
                        }
                    });
                });
            });

            Promise.all(uploadTasks).then(fileIds => {
                resolve(fileIds);
            }).catch(err => {
                reject(err);
            });
        });
    },

    onShow() {
        console.log(1);
        // 从本地存储获取选择的产品
        const selectedProducts = wx.getStorageSync('selectedProducts') || [];
        if (selectedProducts.length > 0) {
            this.setData({
                selectedProducts
            });
            wx.removeStorageSync('selectedProducts');
            this.checkFormStatus();
        }
    },
    beforeenter() {
        console.log('beforeenter');
    },
    enter() {
        console.log('enter');
    },
    afterenter() {
        console.log('afterenter');
    },
    beforeleave() {
        console.log('beforeleave');
    },
    leave() {
        console.log('leave');
    },
    afterleave() {
        console.log('afterleave');
    },
    clickoverlay() {
        console.log('clickoverlay');
    },
});